/* eslint-disable indent */
import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import * as api from './api';
import moment from 'moment';
import {uuid} from './utils';
export const GET_BRANDS_BEGIN = 'GET_BRANDS_BEGIN';
export const GET_BRANDS_SUCCESS = 'GET_BRANDS_SUCCESS';
export const GET_BRANDS_FAIL = 'GET_BRANDS_FAIL';
export const getBrandBegin = () => ({
    type: GET_BRANDS_BEGIN
});
export const getBrandSuccess = data => ({
    type: GET_BRANDS_SUCCESS,
    data
});
export const getBrandFail = () => ({
    type: GET_BRANDS_FAIL,
});

export const getBrands = condition => dispatch => {
    dispatch(getBrandBegin());
    return api.getBrands(condition).then(res => {
        if(res.ok)
            dispatch(getBrandSuccess(res.data));
        else
            dispatch(getBrandFail());
        return res.ok;
    });
};

/*==============================初始化API================================= */
export const getInitData = (code = PAGE_CODE) => dispatch => getCurrentUserPagePermissionsApi(code).then(res => {
    if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
    else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
    return res.isOk;
});
/*==============================查询列表================================= */

export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition
});
export const getListFail = () => ({
    type: GET_LIST_FAIL,
}); //获取列表

export const getList = condition => dispatch => {
    const {startDate, createTime, dealerCode, dealerName, ...props} = condition;
    if(startDate && startDate.length > 0) {
        props.beginStartDate = moment(startDate[0]).toISOString();
        props.endStartDate = moment(startDate[1]).toISOString();
    }
    if(createTime && createTime.length > 0) {
        props.beginCreateTime = moment(createTime[0]).toISOString();
        props.endCreateTime = moment(createTime[1]).toISOString();
    }
    dispatch(getListBegin());
    return api.getList(props).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
        return res.ok;
    });
}; //按钮搜索

export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    dispatch(getList(condition));
}; //分页排序搜索

export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

/*==============================查询action================================= */
//修改查询条件

export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
//重置查询条件

export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});


/* =======================获取详情================================== */
export const GET_ORDER_DETAIL_BEGIN = 'GET_ORDER_DETAIL_BEGIN';
export const GET_ORDER_DETAIL_SUCCESS = 'GET_ORDER_DETAIL_SUCCESS';
export const GET_ORDER_DETAIL_FAIL = 'GET_ORDER_DETAIL_FAIL';
export const getOrderDetailBegin = () => ({
    type: GET_ORDER_DETAIL_BEGIN
});
export const getOrderDetailSuccess = data => ({
    type: GET_ORDER_DETAIL_SUCCESS,
    data
});
export const getOrderDetailFail = () => ({
    type: GET_ORDER_DETAIL_FAIL,
});

export const getOrderDetail = id => dispatch => {
    dispatch(getOrderDetailBegin());
    return api.getOrderDetail(id).then(res => {
        if(res.ok) {
            const {items = [], ...props} = res.data;
            dispatch(getOrderDetailSuccess({
                ...props,
                details: items,
            }));
        } else
            dispatch(getOrderDetailFail());
        return res.ok;
    });
};

/* =======================详情页作废================================== */
export const onClickAbandonForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'orderDetail', 'data'])
        .toJS();
    return api.abandonOrders(id, {
        rowVersion
    });
};

/* =======================详情页提交================================== */
export const onClickEnableForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'orderDetail', 'data'])
        .toJS();
    return api.enableOrders(id, {
        rowVersion
    });
};
/*==============================清除数据================================= */
export const CLEAR_DATA = 'CLEAR_DATA';
export const clearData = () => ({
    type: CLEAR_DATA
});

export const SAVE_SUBMIT_CONDITION = 'SAVE_SUBMIT_CONDITION';
export const saveSubmitCondition = (name, value) => ({
    type: SAVE_SUBMIT_CONDITION,
    name,
    value
});

export const onSubmit = id => (dispatch, getState) => {
    const {
        code,
        name,
        startDate,
        remark,
        brandId,
        dealerId,
        details = [],
        rowVersion
    } = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    const newDetails = details.map(item => {
        const {vehicleItems = [], vehicleCategoryItems = [], id, ...props} = item;
        const categories = vehicleCategoryItems.map(w => {
            const {productCategoryId, partWarrantyCategories = []} = w;
            return {
                productCategoryId,
                partWarrantyCategoryIds: partWarrantyCategories.map(m => ({
                    partWarrantyCategoryId: m.id,
                    remark: m.remark
                }))
            };
        });
        const vins = vehicleItems.map(w => {
            const {vehicleId, parts = []} = w;
            return {
                vehicleId,
                partIds: parts.map(m => ({
                    partId: m.id,
                    remark: m.remark
                }))
            };
        });
        return {
            ...props,
            vehicleCategoryItems: categories,
            vehicleItems: vins,
        };
    });
    if(id)
        return api.updateOrder(id, {
            name,
            startDate,
            items: newDetails,
            remark,
            rowVersion
        });
    return api.addOrder({
        code,
        name,
        startDate,
        remark,
        brandId,
        dealerId,
        items: newDetails
    });
};

// 编辑条款
export const ADD_DETAIL = 'ADD_DETAIL';
export const addDetail = data => ({
    type: ADD_DETAIL,
    data
});

export const onClickCopyDetail = id => dispatch =>
    api.getDetail(id).then(res => {
        if(res.ok) {
            const id = uuid();
            dispatch(addDetail({
                ...res.data,
                id,
            }));
            return id;
        }
        return false;
    });

export const onClickAddDetail = () => dispatch => {
    const id = uuid();
    dispatch(addDetail({
        id,
        vehicleItems: [],
        vehicleCategoryItems: []
    }));
    return Promise.resolve(id);
};

export const DELETE_DETAIL = 'DELETE_DETAIL';
export const deleteDetail = id => ({
    type: DELETE_DETAIL,
    id
});
export const SAVE_DETAIL_CONDITION = 'SAVE_DETAIL_CONDITION';
export const changeDetailCondition = (name, value, detailId) => ({
    type: SAVE_DETAIL_CONDITION,
    name,
    value,
    detailId
});

// 编辑车辆清单
export const DELETE_VEHICLE_DETAIL = 'DELETE_VEHICLE_DETAIL';
export const deleteVehicleDetail = (vehicleId, detailId) => ({
    type: DELETE_VEHICLE_DETAIL,
    vehicleId,
    detailId
});

export const DELETE_ALL_VEHICLE_DETAIL = 'DELETE_ALL_VEHICLE_DETAIL';
export const deleteAllVehicleDetail = detailId => ({
    type: DELETE_ALL_VEHICLE_DETAIL,
    detailId
});

export const SELECT_VEHICLES_TO_DETAILS = 'SELECT_VEHICLES_TO_DETAILS';
export const selectVehicleToDetails = (vehicles = [], detailId) => ({
    type: SELECT_VEHICLES_TO_DETAILS,
    data: vehicles.map(item => ({
        vehicleId: item.id,
        vin: item.vin,
        parts: []
    })),
    detailId
});

export const onSelectVehicleToDetails = (vehicles = [], detailId) => (dispatch, getState) => {
    const {details = []} = getState().getIn(['page', 'appState', 'submitData']).toJS();
    const newVehicle = [];
    // eslint-disable-next-line array-callback-return
    details.map(item => {
        if(item.id === detailId) {
            const {vehicleItems = []} = item;
            // eslint-disable-next-line array-callback-return
            vehicles.map(v => {
                const index = vehicleItems.findIndex(o => o.vehicleId === v.id);
                if(index === -1)
                    newVehicle.push(v);
            });
        }
});
    return dispatch(selectVehicleToDetails(newVehicle, detailId));
};
// 编辑车辆清单 => 备件清单
export const UPDATE_PART_DETAIL = 'UPDATE_PART_DETAIL';
export const updatePartDetail = data => ({
    type: UPDATE_PART_DETAIL,
    data,
});

export const DELETE_PART_DETAIL = 'DELETE_PART_DETAIL';
export const deletePartDetail = (id, vehicleId, detailId) => ({
    type: DELETE_PART_DETAIL,
    vehicleId,
    id,
    detailId
});

export const DELETE_ALL_PART_DETAIL = 'DELETE_ALL_PART_DETAIL';
export const deleteAllPartDetail = (vehicleId, detailId) => ({
    type: DELETE_ALL_PART_DETAIL,
    vehicleId,
    detailId
});

export const SELECT_PARTS_TO_ITEMS = 'SELECT_PARTS_TO_ITEMS';
export const selectPartsToItems = (data, vehicleId, detailId) => ({
    type: SELECT_PARTS_TO_ITEMS,
    vehicleId,
    detailId,
    data
});

export const onSelectParts = (parts = [], vehicleId, detailId) => dispatch => {
    const data = parts.map(item => ({
        id: item.id,
        code: item.code,
        name: item.name,
        remark: item.remark,
    }));
    return dispatch(selectPartsToItems(data, vehicleId, detailId));
};


// 编辑车型清单
export const UPDATE_CATEGORY_DETAIL = 'UPDATE_CATEGORY_DETAIL';
export const updateCategoryDetail = data => ({
    type: UPDATE_CATEGORY_DETAIL,
    data,
});
export const DELETE_CATEGORY_DETAIL = 'DELETE_CATEGORY_DETAIL';
export const deleteCategoryDetail = (productCategoryId, detailId) => ({
    type: DELETE_CATEGORY_DETAIL,
    productCategoryId,
    detailId
});

export const DELETE_ALL_CATEGORY_DETAIL = 'DELETE_ALL_CATEGORY_DETAIL';
export const deleteAllCategoryDetail = detailId => ({
    type: DELETE_ALL_CATEGORY_DETAIL,
    detailId
});

export const SELECT_CATEGORY_TO_DETAILS = 'SELECT_CATEGORY_TO_DETAILS';
export const selectCategoryToDetails = (vehicles = [], detailId) => ({
    type: SELECT_CATEGORY_TO_DETAILS,
    data: vehicles.map(item => ({
        id: uuid(),
        vehicleProperty: item.vehicleProperty,
        productCategoryId: item.id,
        productCategoryCode: item.code,
        productCategoryName: item.name,
        partWarrantyCategories: []
    })),
    detailId
});


// 编辑车型清单 => 备件索赔分类清单
export const UPDATE_PWC_DETAIL = 'UPDATE_PWC_DETAIL';
export const updatePWCDetail = data => ({
    type: UPDATE_PWC_DETAIL,
    data,
});
export const DELETE_PWC_DETAIL = 'DELETE_PWC_DETAIL';
export const deletePWCDetail = (id, productCategoryId, detailId) => ({
    type: DELETE_PWC_DETAIL,
    productCategoryId,
    id,
    detailId
});

export const DELETE_ALL_PWC_DETAIL = 'DELETE_ALL_PWC_DETAIL';
export const deleteAllPWCDetail = (productCategoryId, detailId) => ({
    type: DELETE_ALL_PWC_DETAIL,
    productCategoryId,
    detailId
});

export const SELECT_PWCS_TO_ITEMS = 'SELECT_PWCS_TO_ITEMS';
export const selectPWCsToItems = (data, productCategoryId, detailId) => ({
    type: SELECT_PWCS_TO_ITEMS,
    productCategoryId,
    detailId,
    data
});

export const onSelectPWCs = (parts = [], productCategoryId, detailId) => dispatch => {
    const data = parts.map(item => ({
        id: item.id,
        code: item.code,
        name: item.name,
        remark: item.remark,
    }));
    return dispatch(selectPWCsToItems(data, productCategoryId, detailId));
};


export const saveDetailCondition = (name, value, detailId) => dispatch => {
    dispatch(changeDetailCondition(name, value, detailId));
    if(name !== 'type') return;
    dispatch(deleteAllCategoryDetail(detailId));
    dispatch(deleteAllVehicleDetail(detailId));
};

export const getEditInit = id => dispatch => {
    if(id)
        return dispatch(getOrderDetail(id));
    return dispatch(getBrands());
};


export const SELECT_DEALER_QUERY = 'SELECT_DEALER_QUERY';
export const selectDealerQuery = (data = {}) => ({
    type: SELECT_DEALER_QUERY,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});

export const SELECT_DATA = 'SELECT_DATA';
export const selectData = (data = {}) => ({
    type: SELECT_DATA,
    data: {
        dealerId: data.id,
        dealerCode: data.code,
        dealerName: data.name,
    }
});
